package model

import (
	"fmt"
	"gorm.io/gorm"
	"seckill-system/util"
	"strconv"
)

type GormInventoryDAO struct {
	db *gorm.DB
}

func NewGormInventoryDAO(db *gorm.DB) *GormInventoryDAO {
	return &GormInventoryDAO{
		db: db,
	}
}

func (dao *GormInventoryDAO) ReduceInventory(GiftId int) error {
	client:=GetRedisClient()
	key:=prefix+strconv.Itoa(GiftId)
	n, err:=client.Decr(key).Result()
	if err!=nil{
		util.LogRus.Errorf("decr key %s failed: %v", key, err)
		return err
	}
	if n<0 {
		util.LogRus.Errorf("%d 已无库存，数量-1失败", GiftId)
		return fmt.Errorf("%d 已无库存，数量-1失败", GiftId)
	}
	return nil
}

type Inventory struct {
	Id int `gorm:"column:id; primaryKey, autoIncrement"`
	Name string `gorm:"column:name; varchar(20)"`
	Detail string `gorm:"column:detail; varchar(100)"`
	Picture string `gorm:"column:picture; varchar(200)"`
	Price int `gorm:"column:price;"`
	Number int `gorm:"column:number;"`
}
